<template>
	<div id="ImagePreview">
		<AppHeader bgcolor='transparent'></AppHeader>
		<header class='opteraBar' style='top:0;' v-show="headerIsShow">
			<text class="cuIcon-back fo-50" @click="$pub.back"></text>
			<div class="header-txt" style="">
				<label class="out_of_one">{{ fileInfo.name | FielPathFormat }}</label>
			</div>
		</header>
		<section @click='onShowTopAndBottom'>
			<!-- TODO后期优化啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊   根据图片懒加载获取宽高 分别设置  还有把桶设置成私有 然后用api获取临时在线访问权限 -->
			<img-list class="imgList" :ImgList='imgList_Com' @onChange='ImgListOnChange' :CurrentIndex='CurrentIndex'></img-list>
		</section>
		<footer class='opteraBar' style='bottom:0;' v-show="footIsShow">
			<div class="foot-item" @click="onDownload">
				<text class="cuIcon-down"></text>
				<label>下载</label>
			</div>
			<div class="foot-item" @click="onDelImg">
				<text class="cuIcon-delete"></text>
				<label>删除</label>
			</div>
			<div class="foot-item" @click="onOperate('分享')">
				<text class="cuIcon-share"></text>
				<label>分享</label>
			</div>
			<div class="foot-item" @click="onOperate('旋转')">
				<text class="cuIcon-refresh"></text>
				<label>旋转</label>
			</div>
			<div class="foot-item" @click="onOperate('更多')">
				<text class="cuIcon-more"></text>
				<label>更多</label>
			</div>
		</footer>
	</div>
</template>

<script>
	import {
		mapGetters
	} from 'vuex';
	import {
		API$DelFile
	} from '../../../common/API/file.js';
	import AppHeader from '../../../common/components/AppHeader/index.vue'
	import ImgList from '@/pages/public/SwiperImg/index.vue'
	export default {
		name: 'ImagePreview',
		components: {
			AppHeader,
			ImgList
		},
		data() {
			return {
				fileInfo: "", // 图片信息  页面带参
				imgList: [], // 当前文件夹一组图片信息 页面带参
				CurrentIndex: 0, // 当前展示的图片下表  页面带参
				headerIsShow: true,
				footIsShow: true
			};
		},
		computed: {
			...mapGetters(['File_Get_OssClient']),
			imgList_Com() {
				let arr = []
				this.imgList.forEach(i => arr.push(i.url))
				return arr
			}
		},
		onLoad(opt) {
			this.fileInfo = JSON.parse(opt.opt)
			this.imgList = JSON.parse(opt.imgList)
			this.CurrentIndex = opt.CurrentIndex
		},
		methods: {
			// 监听图片切换
			ImgListOnChange(e) {
				this.fileInfo = this.imgList[e.detail.current]
			},
			// 显示顶部操作栏和底部操作栏
			onShowTopAndBottom() {
				this.headerIsShow = !this.headerIsShow
				this.footIsShow = !this.footIsShow
			},
			onDownload() {
				let that = this
				this.$store.dispatch('Create_AliOssClient');
				let pathName = this.fileInfo.name.split('/')[this.fileInfo.name.split('/').length - 1]; //	asasfdas.video
				let FileName = pathName.slice(0, pathName.match(/[^\.]\w*$/).index - 1); //	asasfdas
				let FileType = this.$tool.getFileType(this.fileInfo.name); //	.video
				let filename = `${FileName}.${FileType}`; // filename为自定义下载后的文件名。
				let response = {
					'content-disposition': `attachment; filename=${encodeURIComponent(filename)}`
				};

				let DownList = null; // 阿里云返回的临时下载地址
				DownList = {
					// fileObj:JSON.parse(JSON.stringify(this.SeletedCurrentDownloadFile[i+pushIndex])),
					fileName: filename,
					fileType: FileType,
					link: this.File_Get_OssClient.signatureUrl(this.fileInfo.name, {
						response
					})
				}
				console.log('阿里云返回的临时下载地址', DownList);

				// #ifdef H5
				var ifr = document.createElement('iframe');
				ifr.style.display = 'none';
				ifr.src = DownList.link;
				document.body.appendChild(ifr);
				setTimeout(function() {
					ifr.remove();
					console.log(444);
				}, 1000);
				// #endif

				// #ifdef APP-PLUS
				let id = that.$tool.create_token();
				let objs = {
					// fileObj:item.fileObj,
					fileName: `${FileName}.${FileType}`,
					// fileSize: res.tempFiles[i].size,
					FileType,
					completeTime: null,
					progress: {
						totalSize: 0,
						curSize: 0
					},
					id,
					Task: plus.downloader.createDownload(DownList.link, {
						filename: '_downloads/yang/'
					}, function(download, status) {
						if (status == 200) {
							that.$pub.Toast('文件下载成功~' + download.filename + '~');

							let currentFilePath = plus.io.convertAbsoluteFileSystem(download.filename); // 取当前文件的绝对路径
							// let currentFilePath = plus.io.convertLocalFileSystemURL(download.filename); // 将本地URL路径转换成平台绝对路径

							// 将本地文件保存到相册 （只保存视频和图片） // TODO 后面写个缓存管理清空内部数据缓存
							if (that.$tool.ImgTypes(that.$tool.getFileType(download.filename))) {
								// console.log(currentFilePath);
								uni.saveImageToPhotosAlbum({
									filePath: currentFilePath,
									success: function() {
										that.$pub.Toast('图片已保存到相册');
										console.log('图片已保存到相册');
									},
									fail(e) {
										console.log('图片保存失败', e);
									}
								});
							} else if (that.$tool.ViodeoTypes(that.$tool.getFileType(download.filename))) {
								uni.saveVideoToPhotosAlbum({
									filePath: currentFilePath,
									success: function() {
										that.$pub.Toast('视频已保存到相册');
										console.log('视频已保存到相册');
									},
									fail(e) {
										console.log('视频保存失败', e);
									}
								});
							}

							that.$store.commit('ADD_CompleteDownloadTask_id', id);
							that.$store.commit('DEL_DownloadTask', id);
						} else {
							that.$pub.Toast('文件下载失败~');
						}
					})
				};
				that.$store.commit('ADD_DownloadTask', objs);
				objs.Task.start();
				objs.Task.addEventListener('statechanged', function(task, status) {
					switch (task.state) {
						case 1: // 开始
							console.log('开始');
							that.$pub.Toast('图片已开始在后台下载~')
							break;
						case 2: // 已连接到服务器
							console.log('连接到服务器');
							break;
						case 3:
							let progress = parseInt((task.downloadedSize / task.totalSize) * 100);
							// console.log(progress)
							objs.progress.totalSize = that.$tool.comFileSize(task.totalSize);
							objs.progress.curSize = that.$tool.comFileSize(task.downloadedSize);
							break;
						case 4:
							console.log('完成');
							objs.completeTime = that.$tool.create_time(new Date(), 'YYYYMMMDDHHMMSS');
							break;
					}
				});
				// #endif
			},
			async onDelImg() {
				console.log(this.fileInfo.name)
				let res = await API$DelFile({
					dir: this.fileInfo.name
				});
				if (res.code == 200) {
					this.$pub.Toast('删除成功~');
					let dirPath = this.fileInfo.name.split('/'),
						dir = ''
					for (let i = 0, item; item = dirPath[i]; i++) {
						if (i == dirPath.length - 1 || i == 0) continue
						dir += item + '/'
					}
					uni.$emit('freshFolderAPI', dir);
					this.$pub.back()
				} else {
					this.$pub.Toast('其他原因~');
				}
			},
			onOperate(e) {

			}
		}
	};
</script>

<style lang="less" scoped="scoped">
	#ImagePreview {
		height: 100vh;
		display: flex;
		flex-direction: column;
		width: 100%;
		background-color: #000000;
		color: #ffffff;
		font-size: 14px;
		cursor: pointer;

		header {
			padding: 10px;
			display: flex;
			align-items: center;
			box-sizing: border-box;
			height: 55px;
		}

		.header-txt {
			width: 100%;
			font-size: 20px;
			display: flex;
			justify-content: center;
		}

		.imgList {
			width: 100%;
			background-size: cover;
			position: absolute;
			top: calc(50% + var(--status-bar-height)/2);
			transform: translate3d(0, -50%, 0);
			max-height: calc(100vh - var(--status-bar-height));
		}

		footer {
			display: flex;
			align-items: center;
			width: 100%;
			position: fixed;
			bottom: 0;
			box-sizing: border-box;
			padding: 4px 0;
			height: 55px;
		}

		.foot-item {
			flex: 1;
			display: flex;
			flex-direction: column;
			align-items: center;
		}
	}

	.iconfont {
		font-size: 30px;
	}

	.out_of_one {
		overflow: hidden;
		text-overflow: ellipsis;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 1;
		/*超出几行省略*/
		width: 280px;
		text-align: center;
	}

	.opteraBar {
		width: 100%;
		// position: absolute;
		z-index: 99;
		background-color: #000;
	}
</style>
